import $ from 'jquery'
import { CanvasWindy } from "./CanvasWindy";
let Cartesian2 = Cesium.Cartesian2
let ScreenSpaceEventType = Cesium.ScreenSpaceEventType
let ScreenSpaceEventHandler = Cesium.ScreenSpaceEventHandler
// export let wa={}
let windyUtil = (function () {
  function windyUtil(layerId) {
    this.globalExtent = []
    this.canvasId = layerId
    this.postRender = null
    this.handler = null
    this.allgrid = null
    this.windData = null
    this.windy = null
    this.windycanvas = null
    this.WindInformation = {
      block_show: false,           //模块化显示
      Wind_speed: 0,               //风速
      wind_direction: "无",         //风向
      wind_field: []               //差值后的向量
    }
    this.windyVisible = true
  }
  windyUtil.prototype.showWindy = function () {
    this.windyVisible = true
    $('#' + this.canvasId).show()
    this.windy.extent = this.globalExtent;
    this.windy.redraw();
  }
  windyUtil.prototype.hideWindy = function () {
    this.windyVisible = false
    $('#' + this.canvasId).hide()
  }
  windyUtil.prototype.getCesiumExtent = function () {
    let canvaswidth = window.innerWidth,
      canvasheight = window.innerHeight * 0.5 - 50;

    let left_top_pt = new Cartesian2(0, 0)
    let left_bottom_pt = new Cartesian2(0, canvasheight)
    let right_top_pt = new Cartesian2(canvaswidth, 0)
    let right_bottom_pt = new Cartesian2(canvaswidth, canvasheight)

    let pick1 = viewer.scene.globe.pick(viewer.camera.getPickRay(left_top_pt), viewer.scene)
    let pick2 = viewer.scene.globe.pick(viewer.camera.getPickRay(left_bottom_pt), viewer.scene)
    let pick3 = viewer.scene.globe.pick(viewer.camera.getPickRay(right_top_pt), viewer.scene)
    let pick4 = viewer.scene.globe.pick(viewer.camera.getPickRay(right_bottom_pt), viewer.scene)
    if (pick1 && pick2 && pick3 && pick4) {
      //将三维坐标转成地理坐标---只需计算左下右上的坐标即可
      let geoPt1 = viewer.scene.globe.ellipsoid.cartesianToCartographic(pick2)
      let geoPt2 = viewer.scene.globe.ellipsoid.cartesianToCartographic(pick3)
      //地理坐标转换为经纬度坐标
      let point1 = [geoPt1.longitude / Math.PI * 180, geoPt1.latitude / Math.PI * 180]
      let point2 = [geoPt2.longitude / Math.PI * 180, geoPt2.latitude / Math.PI * 180]
      // console.log(point1,point2);
      //此时说明extent需要分为东西半球
      if (point1[0] > point2[0]) {
        this.globalExtent = [point1[0], 180, point1[1], point2[1], -180, point2[0], point1[1], point2[1]];
      } else {
        this.globalExtent = [point1[0], point2[0], point1[1], point2[1]];
      }
    } else {
      this.globalExtent = []
    }
  }
  windyUtil.prototype.resizeCanvas = function () {
    if (this.windycanvas == null) {
      return;
    }
    this.windycanvas.width = window.innerWidth;
    this.windycanvas.height = window.innerHeight;
    // console.log(windycanvas.width,windycanvas.height);
    if (this.windy) {
      this.windy._resize(this.windycanvas.width, this.windycanvas.height);
    }
  }
  windyUtil.prototype.createWindLayer = function (windData) {

    if (this.windycanvas != null) {
      return
    }
    let _this = this
    // 开启监听器--无论对当前地球做的任何操作都会监听到
    this.postRender = viewer.scene.postRender.addEventListener(() => {
      _this.getCesiumExtent();
    });
    this.addWindHandle()
    if (this.windycanvas == null) {
      this.windycanvas = document.createElement('canvas');
      this.windycanvas.setAttribute("id", this.canvasId);
      this.windycanvas.style.position = 'absolute'
      this.windycanvas.style["pointer-events"] = "none";
      this.windycanvas.style["z-index"] = 10;
      this.windycanvas.style["top"] = 0;
      this.windycanvas.style["right"] = 0;
      document.getElementById('cesiumContainer').appendChild(this.windycanvas);
    }
    this.resizeCanvas();
    window.οnresize = this.resizeCanvas;
    //风场的参数配置，除了canvas/viewer是必传项，其他可以不传，参数含义见windy.js
    let params = {
      viewer: window.viewer,
      canvas: this.windycanvas,
      canvasWidth: window.innerWidth,
      canvasHeight: window.innerHeight,
      speedRate: 5000,
      particlesNumber: 5000,
      maxAge: 120,
      frameRate: 10,
      color: '#ffffff',
      lineWidth: 1,
    };
    this.windData = windData
    this.analysisWindyData(this.windData)
    this.windy = new CanvasWindy(this.windData, params);
  }

  windyUtil.prototype.addWindHandle = function () {
    let _this = this
    let refreshTimer = -1;
    let mouse_down = false;
    let mouse_move = false;
    this.handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
    //鼠标滚动、旋转后是否需要重新生成风场---如果需要，打开以下注释--旋转或者移动到北半球的时候计算会有问题
    this.handler.setInputAction(function (e) {
      if (_this.windyVisible === true) {
        clearTimeout(refreshTimer);
        $('#' + _this.canvasId).hide()
        // _this.hideWindy();
        setTimeout(function () {
          _this.windy.extent = _this.globalExtent;
          _this.windy.redraw();
          $('#' + _this.canvasId).show()
          // _this.showWindy();
        }, 200);
      }
    }, ScreenSpaceEventType.WHEEL);
    //鼠标左键、右键按下
    this.handler.setInputAction(function (e) {
      mouse_down = true;
    }, ScreenSpaceEventType.LEFT_DOWN);
    this.handler.setInputAction(function (e) {
      mouse_down = true;
    }, ScreenSpaceEventType.RIGHT_DOWN);
    //鼠标移动
    this.handler.setInputAction(function (e) {
      if (_this.windyVisible === true) {
        if (mouse_down) {
          $('#' + _this.canvasId).hide()
          // _this.hideWindy();
          mouse_move = true;
        }
      }

    }, ScreenSpaceEventType.MOUSE_MOVE);
    //鼠标左键、右键抬起
    this.handler.setInputAction(function (e) {
      if (_this.windyVisible === true) {
        if (mouse_down && mouse_move) {
          _this.windy.extent = _this.globalExtent;
          _this.windy.redraw();
        }
        $('#' + _this.canvasId).show()
        // _this.showWindy();
        mouse_down = false;
        mouse_move = false;
        _this.resizeCanvas();
      }
    }, ScreenSpaceEventType.LEFT_UP);
    this.handler.setInputAction(function (e) {
      if (_this.windyVisible === true) {
        if (mouse_down && mouse_move) {
          _this.windy.extent = _this.globalExtent;
          _this.windy.redraw();
        }
        $('#' + _this.canvasId).show()
        // _this.showWindy();
        mouse_down = false;
        mouse_move = false;
      }

    }, ScreenSpaceEventType.RIGHT_UP);
  }
  //根据光标推算风场数据函数
  windyUtil.prototype.GetWindInformation = function (x, y, width, height) {
    let Wind_speed = 0
    let wind_direction = "无"
    let mycolumns = this.WindInformation.wind_field
    if (mycolumns.length !== 0) {
      let columns_x = mycolumns.length
      let columns_y = mycolumns[0].length
      // console.log(x+","+y+"")
      let i = Math.floor(x / (width / columns_x))
      let j = Math.floor(y / (height / columns_y))
      let myfield = mycolumns[i][j]
      if (myfield.length == 3) {
        Wind_speed = myfield[2].toFixed(2)
      } else if (myfield.length == 2) {
        Wind_speed = Math.sqrt(myfield[0] * myfield[0] + myfield[1] * myfield[1]).toFixed(2)
      }
      wind_direction = direction_calculation(myfield[0], myfield[1])
      this.WindInformation.Wind_speed = Wind_speed
      this.WindInformation.wind_direction = wind_direction
    } else {
      this.WindInformation.Wind_speed = 0
      this.WindInformation.wind_direction = "无"
    }

    function direction_calculation(u, v) {
      let fx = 0
      // let v = v2 * (-1)
      let text = "无"
      if (u == 0) {
        if (v > 0) {
          text = "南风"
        } else if (v < 0) {
          text = "北风"
        }
      } else if (v == 0) {
        if (u > 0) {
          text = "西风"
        } else if (u < 0) {
          text = "东风"
        }
      } else {
        if (u > 0 & v > 0) {//第一象限
          // fx = Math.atan(v / u) * 180 / Math.PI
          fx = 270 - Math.atan(v / u) * 180 / Math.PI
          if (fx <= 191.25) {
            text = "南风"
          } else if (fx > 191.25 && fx < 258.76) {
            text = "西南风"
          } else {
            text = "西风"
          }
          // if (fx <= 11.25) {
          //   text = "南风"
          // } else if (fx > 11.25 && fx < 78.76) {
          //   text = "西南风"
          // } else {
          //   text = "西风"
          // }
        }
        else if (u > 0 & v < 0) {//第二象限
          // fx = 180 + Math.atan(v / u) * 180 / Math.PI
          fx = 270 - Math.atan(v / u) * 180 / Math.PI
          if (fx <= 281.25) {
            text = "西风"
          } else if (fx > 281.25 && fx < 348.76) {
            text = "西北风"
          } else {
            text = "北风"
          }
          // if (fx <= 101.25) {
          //   text = "西风"
          // } else if (fx > 101.25 && fx < 168.76) {
          //   text = "西北风"
          // } else {
          //   text = "北风"
          // }
        }
        else if (u < 0 & v < 0) {//第三象限
          // fx = 180 + Math.atan(v / u) * 180 / Math.PI
          fx = 90 - Math.atan(v / u) * 180 / Math.PI
          if (fx <= 11.25) {
            text = "北风"
          } else if (fx > 11.25 && fx < 78.76) {
            text = "东北风"
          } else {
            text = "东风"
          }
          // if (fx <= 191.25) {
          //   text = "东风"
          // } else if (fx > 191.25 && fx < 258.76) {
          //   text = "东北风"
          // } else {
          //   text = "北风"
          // }
        }
        else if (u < 0 & v > 0) {//第四象限
          // fx = 360 + Math.atan(v / u) * 180 / Math.PI
          fx = 90 - Math.atan(v / u) * 180 / Math.PI
          if (fx <= 101.25) {
            text = "东风"
          } else if (fx > 101.25 && fx < 168.76) {
            text = "东南风"
          } else {
            text = "南风"
          }
        }
      }
      return text
    }
  }

  windyUtil.prototype.analysisWindyData = function (windydata) {
    this.allgrid = []
    let p = 0
    let east, north
    if (windydata[0].header.parameterNumberName == "eastward_wind") {
      east = windydata[0]
      north = windydata[1]
    } else {
      east = windydata[1]
      north = windydata[0]
    }
    for (let j = 0; j < north.header.ny; j++) {
      let row = []
      for (let i = 0; i < north.header.nx; i++, p++) {
        row[i] = [east.data[p], north.data[p]]
      }
      this.allgrid[j] = row
    }
  }
  windyUtil.prototype.getWindyDetail = function (coord) {
    let lng = coord[0]
    let lat = coord[1]
    // 与格网序列的数据转换
    // if (lng >= 0) {
    //   lng = Math.floor(lng)
    // } else {
    //   lng = 360 + Math.floor(lng)
    // }
    // lat = 90 - Math.floor(lat)
    // 获取对应的格网序列（此示例为中国区域0.25度规格）
    let xlength = Math.floor((coord[0] - 70) / 0.25)
    let ylength = Math.floor((55 - coord[1]) / 0.25)
    let xdata, ydata
    xdata = parseFloat(this.allgrid[Math.abs(ylength)][Math.abs(xlength)][0])
    ydata = parseFloat(this.allgrid[Math.abs(ylength)][Math.abs(xlength)][1])
    debugger
    let feng = this.direction_calculation(xdata, ydata)
    if (typeof xdata != "number" || typeof ydata != "number") {
      console.error("暂无该区域风向数据！")
      return
    }
    let v = Math.sqrt(Math.pow(xdata, 2) + Math.pow(ydata, 2))
    let angle = this.getWindyAngle(xdata, ydata)
    let result = {
      "direction": feng,
      "level": this.getWindyLevel(v),
      "speed": v.toFixed(2)
    }
    return result
  }
  windyUtil.prototype.direction_calculation = function (u, v) {
    let fx = 0
    // let v = v2 * (-1)
    let text = "无"
    if (u == 0) {
      if (v > 0) {
        text = "南风"
      } else if (v < 0) {
        text = "北风"
      }
    } else if (v == 0) {
      if (u > 0) {
        text = "西风"
      } else if (u < 0) {
        text = "东风"
      }
    } else {
      if (u > 0 & v > 0) {//第一象限
        // fx = Math.atan(v / u) * 180 / Math.PI
        fx = 270 - Math.atan(v / u) * 180 / Math.PI
        if (fx <= 191.25) {
          text = "南风"
        } else if (fx > 191.25 && fx < 258.76) {
          text = "西南风"
        } else {
          text = "西风"
        }
        // if (fx <= 11.25) {
        //   text = "南风"
        // } else if (fx > 11.25 && fx < 78.76) {
        //   text = "西南风"
        // } else {
        //   text = "西风"
        // }
      }
      else if (u > 0 & v < 0) {//第二象限
        // fx = 180 + Math.atan(v / u) * 180 / Math.PI
        fx = 270 - Math.atan(v / u) * 180 / Math.PI
        if (fx <= 281.25) {
          text = "西风"
        } else if (fx > 281.25 && fx < 348.76) {
          text = "西北风"
        } else {
          text = "北风"
        }
        // if (fx <= 101.25) {
        //   text = "西风"
        // } else if (fx > 101.25 && fx < 168.76) {
        //   text = "西北风"
        // } else {
        //   text = "北风"
        // }
      }
      else if (u < 0 & v < 0) {//第三象限
        // fx = 180 + Math.atan(v / u) * 180 / Math.PI
        fx = 90 - Math.atan(v / u) * 180 / Math.PI
        if (fx <= 11.25) {
          text = "北风"
        } else if (fx > 11.25 && fx < 78.76) {
          text = "东北风"
        } else {
          text = "东风"
        }
        // if (fx <= 191.25) {
        //   text = "东风"
        // } else if (fx > 191.25 && fx < 258.76) {
        //   text = "东北风"
        // } else {
        //   text = "北风"
        // }
      }
      else if (u < 0 & v > 0) {//第四象限
        // fx = 360 + Math.atan(v / u) * 180 / Math.PI
        fx = 90 - Math.atan(v / u) * 180 / Math.PI
        if (fx <= 101.25) {
          text = "东风"
        } else if (fx > 101.25 && fx < 168.76) {
          text = "东南风"
        } else {
          text = "南风"
        }
      }
    }
    return text
  }

  windyUtil.prototype.getWindyDirection = function (angle) {
    if ((angle >= 0 && angle <= 22.5) || (angle <= 360 && angle > 337.5)) {
      return "东风"
    }
    if (angle <= 337.5 && angle > 292.5) {
      return "西北风"
    }
    if (angle <= 292.5 && angle > 247.5) {
      return "北风"
    }
    if (angle <= 247.5 && angle > 202.5) {
      return "西南风"
    }
    if (angle <= 202.5 && angle > 157.5) {
      return "东风"
    }
    if (angle <= 157.5 && angle > 112.5) {
      return "东南风"
    }
    if (angle <= 112.5 && angle > 67.5) {
      return "南风"
    }
    if (angle <= 67.5 && angle > 22.5) {
      return "西南风"
    }
  }
  windyUtil.prototype.getWindyAngle = function (u, v) {
    let fx = 0
    if (u > 0 & v > 0) {
      fx = 90 - Math.atan(v / u) * 180 / Math.PI
    } else if (u < 0 & v > 0) {
      fx = 90 - Math.atan(v / u) * 180 / Math.PI
    } else if (u < 0 & v < 0) {
      fx = 270 - Math.atan(v / u) * 180 / Math.PI
    } else if (u > 0 & v < 0) {
      fx = 270 - Math.atan(v / u) * 180 / Math.PI
    } else if (u == 0 & v > 0) {
      fx = 180
    } else if (u == 0 & v < 0) {
      fx = 0
    } else if (u > 0 & v == 0) {
      fx = 270
    } else if (u < 0 & v == 0) {
      fx = 90
    } else if (u == 0 & v == 0) {
      fx = 999.9
    }
    return fx
  }
  windyUtil.prototype.getWindyLevel = function (v) {
    if (v < 0.3) {
      return 0
    }
    if (v >= 0.3 && v < 1.6) {
      return 1
    }
    if (v >= 1.6 && v < 3.4) {
      return 2
    }
    if (v >= 3.4 && v < 5.5) {
      return 3
    }
    if (v >= 5.5 && v < 8.0) {
      return 4
    }
    if (v >= 8.0 && v < 10.8) {
      return 5
    }
    if (v >= 10.8 && v < 13.9) {
      return 6
    }
    if (v >= 13.9 && v < 17.2) {
      return 7
    }
    if (v >= 17.2 && v < 20.8) {
      return 8
    }
    if (v >= 20.8 && v < 24.5) {
      return 9
    }
    if (v >= 24.5 && v < 28.5) {
      return 10
    }
    if (v >= 28.5 && v < 32.7) {
      return 11
    }
    if (v >= 32.7 && v < 37.0) {
      return 12
    }
    if (v >= 37.0 && v < 41.5) {
      return 13
    }
    if (v >= 41.5 && v < 46.2) {
      return 14
    }
    if (v >= 46.2 && v < 51.0) {
      return 15
    }
    if (v >= 51.0 && v < 56.1) {
      return 16
    }
    if (v >= 56.1 && v < 61.2) {
      return 17
    }
    if (v >= 61.2) {
      return 18
    }
  }
  return windyUtil
}())
export { windyUtil }
